
package edu.university.demo.core.shiro;

import java.util.Date;

import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.smallchill.core.toolbox.kit.DateTimeKit;

import edu.university.demo.common.ShiroUser;
import edu.university.demo.core.kits.DateKit;
import edu.university.demo.system.entit.User;
import edu.university.demo.system.service.AccountService;

@Component
public class ShiroFactroy {
	
	@Autowired
	private AccountService accountService;
	
	public User user(String loginName) {
		User user = accountService.findUserByLoginName(loginName);
		// 账号不存在
		if (null == user) {
			throw new UnknownAccountException();
		}
		if(true == user.getIsLock()) {
			if(DateKit.compareDate(new Date(), user.getUnlockTime())) {
				user.recovery();
				accountService.updateUser(user);
			}else
				throw new ExcessiveAttemptsException(DateTimeKit.formatDateTime(user.getUnlockTime()));
		}
		
		return user;
	}

	public ShiroUser shiroUser(User user) {
		
		return new ShiroUser(user.getId(), user.getLoginName(), user.getName());
	}

	/*public List<String> findPermissionsByRoleId(Integer roleId) {
		
		return menuService.findUrlByRoleId(roleId);
	}

	@SuppressWarnings("unchecked")
	public String findRoleNameByRoleId(Integer roleId) {
		
		return roleService.findRoleCodeByRoleId(roleId);
	}*/

	public SimpleAuthenticationInfo info(ShiroUser shiroUser, User user, String realmName) {
		Object credentials = user.getPassword();
		// 密码加盐处理SimpleAuthenticationInfo
		ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
		return new SimpleAuthenticationInfo(shiroUser, credentials, credentialsSalt, realmName);
	}

}
